package com.aiyan.edu.framework.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign远程调用拦截器
 * <p>
 * 把来自上游的http的请求头向下传递
 *
 * @author: zqzhou
 * @create: 2019/11/23 22:20
 **/
public class FeignClientInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (null == requestAttributes) {
            return;
        }

        HttpServletRequest request = requestAttributes.getRequest();

        Enumeration<String> headerNames = request.getHeaderNames();

        if (null == headerNames) {
            return;
        }

        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();

            requestTemplate.header(headerName, request.getHeader(headerName));
        }
    }
}
